import * as XLSX from 'xlsx';
import FileSaver from 'file-saver';

// 字符串转字符流
function s2ab (s) {
  if (typeof ArrayBuffer !== 'undefined') {
    const buf = new ArrayBuffer(s.length);
    const view = new Uint8Array(buf);
    for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
    return buf;
  } else {
    const buf = new Array(s.length);
    for (let j = 0; j != s.length; ++j) buf[j] = s.charCodeAt(j) & 0xff;
    return buf;
  }
}

function exportToExcel (data, filename) {
  const defaultCellStyle = {
    font: { name: 'Verdana', sz: 11, color: 'FF00FF88' },
    fill: { fgColor: { rgb: 'FFFFAA00' } }
  };
  const wopts = {
    bookType: 'xlsx',
    bookSST: false,
    type: 'binary',
    defaultCellStyle,
    showGridLines: false
  };
  let wb = {};
  if (Object.prototype.toString.call(data) === '[object Array]') {
    wb = { SheetNames: ['Sheet1'], Sheets: {}, Props: {} };
    wb.Sheets.Sheet1 = XLSX.utils.aoa_to_sheet(data);
  } else if (Object.prototype.toString.call(data) === '[object Object]') {
    wb = { SheetNames: [], Sheets: {}, Props: {} };
    Object.keys(data).forEach(key => {
      const item = data[key];
      const sheetName = item.name || key;
      wb.SheetNames.push(sheetName);
      wb.Sheets[sheetName] = XLSX.utils.aoa_to_sheet(item.data);
    });
  }

  // 创建二进制对象写入转换好的字节流
  const tmpDown = new Blob([s2ab(XLSX.write(wb, wopts))], {
    type: 'application/octet-stream'
  });
  // 保存文件
  FileSaver.saveAs(tmpDown, filename);
}

export default exportToExcel;
